package cc.dowell.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cc.dowell.config.ContextHolder;
import cc.dowell.mapper.ZoneMapper;
import cc.dowell.pojo.Zone;
import cc.dowell.service.ZoneService;
import cc.dowell.vo.ZoneVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
public class ZoneServiceImpl extends ServiceImpl<ZoneMapper, Zone> implements ZoneService {

    @Autowired
    private ZoneMapper zoneMapper;

    /**
     * 添加园区
     *
     * @param zone
     * @return
     */
    @Override
    public Boolean addZone(Zone zone) {

        Long userId = ContextHolder.getUserId();
        zone.setCreateUserId(userId);
        int b = zoneMapper.insert(zone);
        return b>0;

    }

    /**
     * 删除园区
     * @param id
     * @return okResult
     */
    @Override
    public Boolean deleteZone(Long id) {
        //1.先查询,先查询要删除的园区,是否是这个用户自己的园区
        Long userId = ContextHolder.getUserId();
        Zone zone = zoneMapper.selectById(id);
        int b = 0;
        if(userId.equals(zone.getCreateUserId())){
            //是自己创建的，可以进一步删除
             b = zoneMapper.deleteById(id);
        }else {
            throw new RuntimeException("无法删除非自己创建的园区");
        }
        return b>0;
    }

    /**
     * 编辑园区
     * @param zone
     * @return
     */
    @Override
    public Boolean updateZone(Zone zone) {
        int b = zoneMapper.updateById(zone);
        return b>0;
    }

    /**
     * 园区详细信息
     * @param id
     * @return
     */
    @Override
    public ZoneVo zoneInfo(Long id) {
        LambdaQueryWrapper<Zone> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Zone::getId, id);
        List<Zone> zoneList = zoneMapper.selectList(lambdaQueryWrapper);
        if(zoneList.size()>0){
            ZoneVo zoneVo = new ZoneVo();
            BeanUtils.copyProperties(zoneList.get(0),zoneVo);
            return zoneVo ;
        }
        return null;
    }

    @Override
    public IPage<ZoneVo> selectZonePage(Page<Zone> page) {
        LambdaQueryWrapper<Zone> lqw = new LambdaQueryWrapper<>();
        Page<Zone> zonePage = zoneMapper.selectPage(page, lqw);
        // Long userId = ContextHolder.getUserId();
        IPage<ZoneVo> zoneVoPage = zonePage.convert(e -> {
            ZoneVo zoneVo = new ZoneVo();
            BeanUtils.copyProperties(e, zoneVo);
            return zoneVo;
        });


        return zoneVoPage;
    }

}